import json
import datetime
import matplotlib.pyplot as plt
import time
import qb_database
import config
from collections import OrderedDict
from pylab import *
import sys


def dic_make(list_name,dict_name):
    '''make dict to list

    :param list_name:[[key,int],...] list must have key and value like [['shot1',20],['shot2',30],['shot1',40]]
    :param dict_name: just a name to return
    :return: {'shot1':60,'shot2':30}
    '''
    for i in list_name :
        if not dict_name.has_key(i[0]):
            dict_name[i[0]] = 0
        dict_name[i[0]] += i[1]
    return dict_name


def sort_key(old_dict, reverse = False):
    keys = sorted(old_dict.keys(),reverse=reverse)
    new_dict = OrderedDict()
    for key in keys:
        new_dict[key] = old_dict[key]
    return new_dict


def get_the_subjob_week(timestart_qube_sta, timestart_qube_end):
    """
    The number of subjob and complete subjob
    :param timestart_qube_sta: submit_time like '2019-01-10 15:00:00'
    :param timestart_qube_end: end_time
    :return:
    """
    list_per_subjob = []
    list_per_subjob_complete = []
    list_per_subjob_fail = []
    list_per_subjob_dict = {}
    list_per_subjob_complete_dict = {}
    list_per_subjob_fail_dict = {}
    all_subjob = 0
    all_complete = 0
    fail = 0
    q = qb_database.QubeDatabase()
    job = q.job(
        query_field='id,prod_show,prod_shot,prod_seq,status,timesubmit,timestart,timeout,timecomplete,todo,todotally,name',
        query='(status != 261) and (status != 48) and (timesubmit between %s and %s) and (prod_show = "ANBO")' % (
            timestart_qube_sta, timestart_qube_end))
    # job_len = len(job)
    for i in job:
        todotally = map(int, i['todotally'].split())
        all_subjob += int(i['todo'])
        timesubmit = time.strftime('%Y-%m-%d', time.localtime(i['timesubmit'] + config.QUBE_TIME))
        list_per_subjob.append([timesubmit, i['todo']])
        if i['status'] == 16:
            all_complete = todotally[2]
            list_per_subjob_complete.append([timesubmit, all_complete])
        if i['status'] == 32:
            fail = todotally[5]
            list_per_subjob_fail.append([timesubmit, fail])

    dic_make(list_per_subjob, list_per_subjob_dict)
    dic_make(list_per_subjob_complete, list_per_subjob_complete_dict)
    dic_make(list_per_subjob_fail,list_per_subjob_fail_dict)

    list_per_subjob_complete_dict = sort_key(list_per_subjob_complete_dict)
    list_per_subjob_dict = sort_key(list_per_subjob_dict)
    list_per_subjob_fail_dict = sort_key(list_per_subjob_fail_dict)

    return list_per_subjob_complete_dict, list_per_subjob_dict,list_per_subjob_fail_dict


def get_data(data_complete, data_subjob):
    week_result_com = OrderedDict()
    week_result_sub = OrderedDict()
    for key,value in data_complete.items():
        week_num = datetime.datetime.strptime(key, "%Y-%m-%d").strftime('%W')
        if week_num not in week_result_com.keys():
            week_result_com[week_num] = value
        else:
            week_result_com[week_num] += value

    for key,value in data_subjob.items():
        week_num = datetime.datetime.strptime(key, "%Y-%m-%d").strftime('%W')
        if week_num not in week_result_sub.keys():
            week_result_sub[week_num] = value
        else:
            week_result_sub[week_num] += value
  
    key_list = ["weeknum  :"]
    sub_list = ["submitjob:"]
    comp_list = ["completed:"]

    for key,value in week_result_sub.items():
        key_list.append('wk'+key)
        sub_list.append(int(value))
        comp_list.append(week_result_com[key])
    print '    '.join(repr(e) for e in key_list)
    print '    '.join(repr(e) for e in sub_list)
    print '    '.join(repr(e) for e in comp_list)

if __name__ == "__main__":
    timeend = datetime.date.today() - datetime.timedelta(days=1)
    time_end_stamo = time.strptime(str(timeend) + ' 00:00:00', "%Y-%m-%d %H:%M:%S")
    timeend_default = time.strftime( "%Y-%m-%d %H:%M:%S",time_end_stamo)
    time_start = datetime.date.today() - datetime.timedelta(days=30)
    time_start_stamo = time.strptime(str(time_start) + ' 00:00:00', "%Y-%m-%d %H:%M:%S")
    timestart_default = time.strftime("%Y-%m-%d %H:%M:%S",time_start_stamo)

    timestart = raw_input('Plese input the Date of start (Exam:\033[22;36m %s \033[0m) :' % timestart_default)
    if timestart == '':
        timestart = timestart_default
        print '\033[22;36m %s \033[0m' % timestart
    timeend = raw_input('Plese input the Date of end (Exam:\033[22;36m %s \033[0m) :' % timeend_default)
    if timeend == '':
        timeend = timeend_default
        print '\033[22;36m %s \033[0m' % timeend
    
    timestart_arr_sta = time.strptime(timestart, "%Y-%m-%d %H:%M:%S")
    time_start_local = time.localtime(time.mktime(timestart_arr_sta))
    timestart_qube_sta = int(time.mktime(timestart_arr_sta)) - config.QUBE_TIME
    timestart_arr_end = time.strptime(timeend, "%Y-%m-%d %H:%M:%S")
    time_end_local = time.localtime(time.mktime(timestart_arr_end))
    timestart_qube_end = int(time.mktime(timestart_arr_end)) - config.QUBE_TIME
    data_complete, data_subjob, data_faile = get_the_subjob_week(timestart_qube_sta, timestart_qube_end)
    get_data(data_complete, data_subjob)